package com.pinyoumei.app.activity.integral;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BaseActivity;
import com.pinyoumei.app.activity.OrderPayActivity;
import com.pinyoumei.app.activity.wallet.WalletCouponDialog1;
import com.pinyoumei.app.bean.GenerateBean;
import com.pinyoumei.app.bean.GoodDetailsBean;
import com.pinyoumei.app.bean.IntegralDetailsBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.view.dialog.BottomDialog;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.ig.DefaultImageDownloader;

import org.reactivestreams.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-10.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-10        Administrator             新增Person类
 * 2021-08-10        Administrator             增加sex属性
    商品详情
 */
public class IntegralDetailActivity extends BaseActivity implements View.OnClickListener {

//    private BadgeView badgeView;
    private int sckNum;
    private IntegralDetailsBean integralDetailsBean;
    private String goods_id = "";
    private List<String> image_list = new ArrayList<>();
    private Banner banner;
    private TextView tv_sale_price;
    private TextView tvSaleNum;
    private TextView tvStockNum;
    private TextView tvEquipmentDesc;
    private TextView tvGoodsName;
    private Subscriber subscriber2;
    private TextView tv_1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral_detail);
        integralDetailsBean = (IntegralDetailsBean) getIntent().getSerializableExtra("integralDetailsBean");
        goods_id = getIntent().getStringExtra("goods_id");

        InitWidget();
        generate();
        InitData();
    }



    private void InitWidget() {
        RichText.initCacheDir(this);
        RichText.debugMode = true;
        ImageView iv_close = findViewById(R.id.iv_close);
        iv_close.setOnClickListener(this);
//        LinearLayout ll_car = findViewById(R.id.ll_car);
//        ll_car.setOnClickListener(this);
//        Button bt_add_car = findViewById(R.id.bt_add_car);
//        bt_add_car.setOnClickListener(this);
        Button bt_buy = findViewById(R.id.bt_buy);
        bt_buy.setOnClickListener(this);

        banner = findViewById(R.id.banner);
        tvGoodsName = findViewById(R.id.tv_goods_name);
        tv_sale_price = findViewById(R.id.tv_sale_price);
        tvSaleNum = findViewById(R.id.tv_sale_num);
        tvStockNum = findViewById(R.id.tv_stock_num);
        tvEquipmentDesc = findViewById(R.id.tv_equipment_desc);
        tv_1 = findViewById(R.id.tv_1);
    }

    private void InitData() {
        if (integralDetailsBean != null) {

            if (integralDetailsBean.getResult().getGoods_detail_info().getBanner_images() != null) {
                String[] tags = integralDetailsBean.getResult().getGoods_detail_info().getBanner_images().split(",");

                if (tags != null && tags.length > 0) {
                    for (int i = 0; i < tags.length; i++) {
                        image_list.add(tags[i]);
                    }
                    initBanner();
                }
            }

            tvGoodsName.setText(integralDetailsBean.getResult().getGoods_detail_info().getGoods_name() + "");
//            tv_1.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG); //中划线
//            tvMarketPrice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG); //中划线
            tv_sale_price.setText( integralDetailsBean.getResult().getGoods_detail_info().getNeed_score() + "");

            tvSaleNum.setText("销量：" + integralDetailsBean.getResult().getGoods_detail_info().getSale_num() + "件");
            String mStr = integralDetailsBean.getResult().getGoods_detail_info().getStock_num();
            sckNum = Integer.parseInt(mStr);
            tvStockNum.setText("库存：" + sckNum + "件");




        }

        RichText.from(integralDetailsBean.getResult().getGoods_detail_info().getGoods_detail())
                .autoFix(true)
                .showBorder(false)
                .autoPlay(true)
                .imageDownloader(new DefaultImageDownloader())
                .into(tvEquipmentDesc);
    }





    private void initBanner() {
        //第二个Banner

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置Banner的样式BannerConfig.CIRCLE_INDICATOR
        banner.setImages(image_list); //存放图片的list集合url
        banner.setBannerAnimation(Transformer.ZoomOutSlide);//设置Banner轮播的动画特效的样式
        //banner.setPageTransformer(true,)//自定义轮播动画
        banner.setImageLoader(new GlideImageLoader());//设置图片加载器
        banner.isAutoPlay(true);//设置默认为自动轮播
        banner.setDelayTime(3000);//设置轮播间隔时间
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);


        banner.start();

    }

    //使用Glide加载器
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {

            //Glide 加载图片

            Glide.with(context).load(path).into(imageView);

//            //设置图片圆角角度
//            RoundedCorners roundedCorners = new RoundedCorners(DensityUtil.dp2px(5));
//            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
//            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
//            Glide.with(context)
//                    .load(path)
//                    .apply(options)
//                    .into(imageView);

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.iv_close :
        		finish();
        		break;

//        		case R.id.ll_car :
//        		//购物车
//        		break;
//
//            case R.id.bt_add_car :
//                //加入购物车
//                break;

            case R.id.bt_buy:
                //立即购买
                if (integralDetailsBean!=null){
                    BottomDialog bottomDialog = new BottomDialog(IntegralDetailActivity.this,R.layout.dialog_buy_integral);
                    bottomDialog.show();
                    ImageView iv_bg = bottomDialog.findViewById(R.id.iv_bg);
                    //Glide 加载图片
                    RequestOptions placeholder = new RequestOptions().placeholder(R.mipmap.ic_error_loading);
                    if (image_list!=null && image_list.size()>0){
                        Glide.with(IntegralDetailActivity.this).load(image_list.get(0)).apply(placeholder).into(iv_bg);

                    }

                    EditText edittext_num = bottomDialog.findViewById(R.id.edittext_pos_num);
                    TextView tv_title = bottomDialog.findViewById(R.id.tv_title);

                    tv_title.setText(integralDetailsBean.getResult().getGoods_detail_info().getGoods_name());

                    TextView tv_sale_amount = bottomDialog.findViewById(R.id.tv_sale_amount);
                    tv_sale_amount.setText(integralDetailsBean.getResult().getGoods_detail_info().getNeed_score());

                    RelativeLayout relative_remove = bottomDialog.findViewById(R.id.relative_remove);
                    relative_remove.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击减号
                            if (Integer.valueOf(edittext_num.getText().toString().trim()) <= 1) {
                                return;
                            }
                            int b = Integer.valueOf(edittext_num.getText().toString().trim()) - 1;
                            edittext_num.setText(b + "");
                        }
                    });

                    RelativeLayout relative_add = bottomDialog.findViewById(R.id.relative_add);
                    relative_add.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击加号
                            int a = Integer.valueOf(edittext_num.getText().toString().trim()) + 1;
                            edittext_num.setText(a + "");
                        }
                    });
                    Button bt_sure = bottomDialog.findViewById(R.id.bt_sure);
                    bt_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottomDialog.dismiss();
                            int editNum = Integer.parseInt(edittext_num.getText().toString().trim());
                            if(editNum > sckNum){
                                editNum = sckNum;
                            }
                            Intent intent = new Intent(IntegralDetailActivity.this, IntegralOrderPayActivity.class);
                            intent.putExtra("goods_id",goods_id);
                            intent.putExtra("goods_num",editNum);
                            intent.putExtra("order_type",2);
                            startActivity(intent);
                        }
                    });
                }

                break;
        	default:
        		break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RichText.recycle();



    }

    private void generate() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId",SPUtils.getAppUserId(IntegralDetailActivity.this));
        map.put("goodsId", goods_id);
        OkGo.<String>post(Constants.generate)
                .params("userId", SPUtils.getAppUserId(IntegralDetailActivity.this))
                .params("goodsId", goods_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    private void setData(Response<String> response) {
                        GenerateBean generateBean = gson.fromJson(response.body(), GenerateBean.class);
                        if (generateBean.getCode() >= 0) {
                            if(generateBean.getResult().isQualify()){
                                Utils.red_package_amount = Double.parseDouble(generateBean.getResult().getAmount());
                                new WalletCouponDialog1(IntegralDetailActivity.this,0,new int[]{}).show();
                            }
                        } else {
                            Toast.makeText(IntegralDetailActivity.this, generateBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }
}
